package ogr.ktjy.demo.comfig;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.ktjy.demo.comfig.CustoRealn;
import org.ktjy.demo.entity.SysRight;
import org.ktjy.demo.service.ISysRightService;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean

    public Realm realm() {
        return new CustoRealn();

    }

    @Bean
    public SecurityManager securityManager() {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();

        securityManager.setRealm(realm());
        return securityManager;
    }


    @Resource
    ISysRightService sysRightService;

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean() {
//        DefaultSecurityManager securityManager = new DefaultSecurityManager();
//        securityManager.setRealm(new CustoRealn());

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setSuccessUrl("/main");
        //那些请求需要权限验证，那些请求可以匿名访问
        //key 标识资源路径 value shiro内置的过滤规则
        Map<String, String> resoucesMap = new LinkedHashMap<>();
        resoucesMap.put("/static/**", "anon");



        List<SysRight> rightList = sysRightService.list();
        for (SysRight right: rightList){
            if (StringUtils.isNotEmpty(right.getRightUrl().trim())) {
                resoucesMap.put(right.getRightUrl(),"perms["+right.getRightCode()+"]");
            }
        }
        return shiroFilterFactoryBean;
    }
}
